import React, { useEffect, useState } from 'react';
import { Card, Table, Button, DialogPlugin, MessagePlugin, Input, Select, Tag, Switch } from 'tdesign-react';
import { SearchIcon, AddIcon, EditIcon, DeleteIcon, RefreshIcon } from 'tdesign-icons-react';
import { JupiterCategory, JupiterCategoryQuery, JupiterCategoryForm } from '../../types/categoryTypes';
import { formatTime } from '../../utils/timeutil';
import {
    fetchCategoryList,
    createCategory,
    updateCategory,
    deleteCategory,
    fetchCategoryTree
} from '../../services/categoryService';
import CategoryForm from './components/CategoryForm';

export default function CategoryPage() {
    const [categoryList, setCategoryList] = useState<JupiterCategory[]>([]);
    const [loading, setLoading] = useState(false);
    const [formVisible, setFormVisible] = useState(false);
    const [editingCategory, setEditingCategory] = useState<Partial<JupiterCategory>>();
    const [title, setTitle] = useState('新增分类');

    // 搜索条件
    const [searchName, setSearchName] = useState('');
    const [searchParent, setSearchParent] = useState('');
    const [searchActive, setSearchActive] = useState('');

    // 分页
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    // 父分类选项
    const [parentOptions, setParentOptions] = useState<{ label: string; value: string }[]>([]);

    const getList = async () => {
        setLoading(true);
        try {
            const params: JupiterCategoryQuery = {
                name: searchName || undefined,
                parentUuid: searchParent || undefined,
                isActive: searchActive ? searchActive === 'true' : undefined,
                page: pagination.current,
                size: pagination.pageSize,
            };
            const response = await fetchCategoryList(params);
            if (response.code === 200) {
                setCategoryList(response.data.records || []);
                setPagination(prev => ({
                    ...prev,
                    total: response.data.total || 0,
                }));
            }
        } catch (error) {
            MessagePlugin.error('获取分类列表失败');
        } finally {
            setLoading(false);
        }
    };

    const getParentOptions = async () => {
        try {
            const response = await fetchCategoryTree();
            if (response.code === 200) {
                const options = response.data.map((item: JupiterCategory) => ({
                    label: item.name,
                    value: item.uuid,
                }));
                setParentOptions([{ label: '无父分类', value: '' }, ...options]);
            }
        } catch (error) {
            console.error('获取父分类选项失败:', error);
        }
    };

    const handleSearch = () => {
        setPagination(prev => ({ ...prev, current: 1 }));
        getList();
    };

    const handleReset = () => {
        setSearchName('');
        setSearchParent('');
        setSearchActive('');
        setPagination(prev => ({ ...prev, current: 1 }));
        getList();
    };

    const handleCreate = () => {
        setEditingCategory({});
        setTitle('新增分类');
        setFormVisible(true);
    };

    const handleEdit = (record: JupiterCategory) => {
        setEditingCategory(record);
        setTitle('编辑分类');
        setFormVisible(true);
    };

    const handleDelete = (record: JupiterCategory) => {
        DialogPlugin.confirm({
            header: '确认删除',
            body: `确定要删除分类"${record.name}"吗？`,
            onConfirm: async () => {
                try {
                    const response = await deleteCategory(record.uuid);
                    if (response.code === 200) {
                        MessagePlugin.success('删除成功');
                        getList();
                    } else {
                        MessagePlugin.error(response.message || '删除失败');
                    }
                } catch (error) {
                    MessagePlugin.error('删除失败');
                }
            },
        });
    };

    const handleFormSubmit = async (formData: JupiterCategoryForm) => {
        try {
            let response;
            if (editingCategory?.uuid) {
                response = await updateCategory(editingCategory.uuid, formData);
            } else {
                response = await createCategory(formData);
            }

            if (response.code === 200) {
                MessagePlugin.success(editingCategory?.uuid ? '更新成功' : '创建成功');
                setFormVisible(false);
                getList();
                getParentOptions(); // 刷新父分类选项
            } else {
                MessagePlugin.error(response.message || '操作失败');
            }
        } catch (error) {
            MessagePlugin.error('操作失败');
        }
    };

    const handlePageChange = (pageInfo: any) => {
        setPagination(prev => ({
            ...prev,
            current: pageInfo.current,
            pageSize: pageInfo.pageSize,
        }));
    };

    const columns = [
        {
            colKey: 'name',
            title: '分类名称',
            width: 200,
        },
        {
            colKey: 'parentName',
            title: '父分类',
            width: 150,
            cell: ({ row }: any) => row.parentName || '-',
        },
        {
            colKey: 'description',
            title: '描述',
            width: 200,
            cell: ({ row }: any) => (
                <div style={{ maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {row.description || '-'}
                </div>
            ),
        },
        {
            colKey: 'sortOrder',
            title: '排序',
            width: 80,
        },
        {
            colKey: 'articleCount',
            title: '文章数量',
            width: 100,
        },
        {
            colKey: 'isActive',
            title: '状态',
            width: 100,
            cell: ({ row }: any) => (
                <Tag theme={row.isActive ? 'success' : 'default'}>
                    {row.isActive ? '启用' : '禁用'}
                </Tag>
            ),
        },
        {
            colKey: 'createTime',
            title: '创建时间',
            width: 180,
            cell: ({ row }: any) => formatTime(row.createTime),
        },
        {
            colKey: 'operation',
            title: '操作',
            width: 150,
            cell: ({ row }: any) => (
                <div style={{ display: 'flex', gap: 8 }}>
                    <Button
                        theme="primary"
                        variant="text"
                        icon={<EditIcon />}
                        onClick={() => handleEdit(row)}
                    >
                        编辑
                    </Button>
                    <Button
                        theme="danger"
                        variant="text"
                        icon={<DeleteIcon />}
                        onClick={() => handleDelete(row)}
                    >
                        删除
                    </Button>
                </div>
            ),
        },
    ];

    useEffect(() => {
        getList();
        getParentOptions();
    }, [pagination.current, pagination.pageSize]);

    return (
        <Card title="分类管理">
            {/* 搜索区域 */}
            <div style={{ marginBottom: 16, padding: '16px 0', borderBottom: '1px solid #e7e7e7' }}>
                <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
                    <Input
                        placeholder="分类名称"
                        value={searchName}
                        onChange={(value) => setSearchName(value as string)}
                        style={{ width: 200 }}
                    />
                    <Select
                        placeholder="父分类"
                        value={searchParent}
                        onChange={(value) => setSearchParent(value as string)}
                        style={{ width: 200 }}
                        options={parentOptions}
                        clearable
                    />
                    <Select
                        placeholder="状态"
                        value={searchActive}
                        onChange={(value) => setSearchActive(value as string)}
                        style={{ width: 120 }}
                        options={[
                            { label: '启用', value: 'true' },
                            { label: '禁用', value: 'false' },
                        ]}
                        clearable
                    />
                    <Button theme="primary" icon={<SearchIcon />} onClick={handleSearch}>
                        搜索
                    </Button>
                    <Button theme="default" onClick={handleReset}>
                        重置
                    </Button>
                </div>
            </div>

            {/* 操作按钮 */}
            <div style={{ marginBottom: 16, textAlign: 'right' }}>
                <Button theme="primary" icon={<AddIcon />} onClick={handleCreate}>
                    新增分类
                </Button>
            </div>

            {/* 表格 */}
            <Table
                data={categoryList}
                rowKey="uuid"
                columns={columns}
                loading={loading}
                pagination={{
                    current: pagination.current,
                    pageSize: pagination.pageSize,
                    total: pagination.total,
                    onChange: handlePageChange,
                }}
            />

            {/* 表单弹窗 */}
            <CategoryForm
                visible={formVisible}
                title={title}
                editingData={editingCategory}
                onClose={() => setFormVisible(false)}
                onSubmit={handleFormSubmit}
            />
        </Card>
    );
}